﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebTraderLiteCL;

namespace WebTraderLite
{
    public partial class Home : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {}

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            
            Stock stk = new Stock(tbSearchSymbol.Text.Trim());

            if (stk.CompanyName.Equals("NULL"))
            {
                
                Label lbl = new Label();
                lbl.Text = "Stock sybmol " + stk.Symbol + " not found. ";
                lbl.Font.Bold = true;
                DBTransactions trans = new DBTransactions();
                List<Stock> list = new List<Stock>();
                list = trans.retriveSuggestionforStockSymbol(tbSearchSymbol.Text.Trim());
                
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                       if(i==list.Count-1) lbl.Text += "Try " + list.ElementAt(i).Symbol + " for company: " + list.ElementAt(i).CompanyName;
                       else lbl.Text+=" Try " + list.ElementAt(i).Symbol + " for company: " + list.ElementAt(i).CompanyName+ " or";
                    }
                }
                phFailSearch.Controls.Add(lbl);

                //Hide controls 
                tblStockInfo.Visible = false;
                hrefAutoBuy.Visible = false;
                hrefBuy.Visible = false;
                lbMonitor.Visible = false;
                btn1M.Visible = false;
                btn1Wk.Visible = false;
                btn3M.Visible = false;
                btn6M.Visible = false;
                btn1Y.Visible = false;

            }
            else
            {

                tblRowSymbol.Cells.Add(new TableCell());
                tblRowSymbol.Cells[1].Text = stk.Symbol;

                DBTransactions trans = new DBTransactions();
                trans.insertIntoStock(stk);

                //Set up the hyperlink navigat url's and display the controls
                hrefBuy.NavigateUrl = "~/Pages/BuyStock.aspx?stock=" + stk.Symbol;
                hrefBuy.Visible = true;
                hrefAutoBuy.NavigateUrl = "~/Pages/AutoBuy.aspx?stock=" + stk.Symbol;
                hrefAutoBuy.Visible = true;
                lbMonitor.Visible = true;


                tblRowCompany.Cells.Add(new TableCell());
                tblRowCompany.Cells[1].Text = stk.CompanyName;

                tblRowPrice.Cells.Add(new TableCell());
                tblRowPrice.Cells[1].Text = stk.Price.ToString("C"); //format as currency

                tblRowShareNo.Cells.Add(new TableCell());
                tblRowShareNo.Cells[1].Text = stk.SharesOutstanding.ToString(); //format as currency

                
                tblStockInfo.Visible = true;
                
                //Show the graph buttons
                btn1M.Visible = true;
                btn1Wk.Visible = true;
                btn3M.Visible = true;
                btn6M.Visible = true;
                btn1Y.Visible = true;
                
                DateTime fromDate = DateTime.Today.AddMonths(-3); //default to 3 months of data

                //Update the graphdisplay
                updateGraph(fromDate);

            }
        }

        //Handle the linkbutton for monitor and add stock to monitor in database for the user
        public void lbMonitor_Click(object sender, EventArgs e)
        {
            DBTransactions db = new DBTransactions();
            String userName = HttpContext.Current.User.Identity.Name;
            String stockSym = tbSearchSymbol.Text.Trim();

            //Insert stock into list of user's monitored stocks
            db.insertIntoMonitor(userName, stockSym.ToUpper());
            Response.Redirect("~/Pages/Transactions.aspx");
        }
        //Update asynchronous panel for 1 week of graph data
        protected void btn1Wk_Click(object sender, EventArgs e)
        {
            DateTime fromDate = DateTime.Today.AddDays(-7);
            updateGraph(fromDate);
        }

        //Update asynchronous panel for 1 months of graph data
        protected void btn1M_Click(object sender, EventArgs e)
        {
            DateTime fromDate = DateTime.Today.AddMonths(-1); 

            //Update the graphdisplay
            updateGraph(fromDate);
        }

        //Update asynchronous panel for 3 months of graph data
        protected void btn3M_Click(object sender, EventArgs e)
        {
            DateTime fromDate = DateTime.Today.AddMonths(-3); 

            //Update the graphdisplay
            updateGraph(fromDate);
        }

        //Update asynchronous panel for 6 months of graph data
        protected void btn6M_Click(object sender, EventArgs e)
        {
            DateTime fromDate = DateTime.Today.AddMonths(-6); 

            //Update the graphdisplay
            updateGraph(fromDate);
        }

        //Update asynchronous panel for 6 months of graph data
        protected void btn1Y_Click(object sender, EventArgs e)
        {
            DateTime fromDate = DateTime.Today.AddYears(-1);

            //Update the graphdisplay
            updateGraph(fromDate);
        }

        private void updateGraph(DateTime fromDate)
        {
            Stock stk = new Stock(tbSearchSymbol.Text.Trim());
            //Graph stock history
            stockDataQuery qry = new stockDataQuery();
            DateTime toDate = DateTime.Today;

            List<HistoricalStockData> history = qry.getHistoricalData(tbSearchSymbol.Text.Trim(), fromDate, toDate);
            if (history != null)
            {
                foreach (HistoricalStockData elem in history)
                {
                    stockChart.Series["seriesPriceHistory"].Points.AddXY(elem.Date, elem.Close);
                    stockChart.Series["seriesVolHistory"].Points.AddXY(elem.Date, elem.Volume);
                }

                double maxClose = history.Max(t => t.Close);
                double minClose = history.Min(t => t.Close);

                //Set the axis titles
                stockChart.Titles.Add(stk.CompanyName + " history from " + fromDate.ToShortDateString() + " to " + toDate.ToShortDateString());
                stockChart.ChartAreas["chartAreaPriceHistory"].AxisX.Title = "Date";
                stockChart.ChartAreas["chartAreaPriceHistory"].AxisY.Title = "Closing Price ($)";

                stockChart.ChartAreas["chartAreaVolume"].AxisX.Title = "Date";
                stockChart.ChartAreas["chartAreaVolume"].AxisY.Title = "Volume";

                //Set the max and min of the Y-axis
                stockChart.ChartAreas["chartAreaPriceHistory"].AxisY.Maximum = maxClose;
                stockChart.ChartAreas["chartAreaPriceHistory"].AxisY.Minimum = minClose;
            }
            else
            {
                Label lblChartDataFail = new Label();
                lblChartDataFail.Text = "Chart Currently Unavailable. Try Again Later.";
                lblChartDataFail.ForeColor = System.Drawing.Color.Red;
                phFailSearch.Controls.Add(lblChartDataFail);
            }
        }


    }
}